import Tkinter as Tk
import subprocess
import sys
from Tkinter import *
import thread
import time
import tkFileDialog

def receive_thread(popen,id):
    global mylist,clientid,arguments
    arguments='empty'
    while True:
        next_line = popen.stdout.readline().strip()
        print next_line
        parts=next_line.split('&&')
        if parts[0]=="$$ID":
            clientid=parts[1]
            v11.set(parts[1])
        elif parts[0]=="$$LIST":
            mylist.delete(0, END) # clear list box
            length=len(parts)
            for i in range(1,length):
                mylist.insert(END, parts[i])
        elif parts[0]=='$$MSSG':
            v1.set(parts[2])
        elif parts[0]=='$$VIDEO':
            arguments=parts[1]
            remote=arguments.split(':')
            host_temp=remote[0]
            host=host_temp.split('/')[1]
            port=remote[1]
            Execute_File2(host, port)
            arguments='empty'
        elif parts[0]=='$$FILE':
            arguments=parts[1]
            remote=arguments.split(':')
            host_temp=remote[0]
            host=host_temp.split('/')[1]
            port=remote[1]
            Execute_File3(host, port, filepath)
            arguments='empty'

def get_active(mylsit,id):
    global active
    while True:
        time.sleep(1)
        if mylist.get(ACTIVE)!='empty':
            active=mylist.get(ACTIVE)
    thread.exit_thread()
def stop():
    popen.stdin.write('$$END'+'\n')

def refresh():
    popen.stdin.write('$$REQUEST'+'\n')

def send():
    popen.stdin.write('$$MSSG'+'&&'+active+'&&'+v2.get() +'\n')
    v2.set('')
    
def videoC():
    popen.stdin.write('$$VIDEO'+'&&'+active+'\n')
    
def fileC():
    global filepath
    filepath='empty'
    filepath=tkFileDialog.askopenfilename()
    print filepath
    if filepath!='':
        popen.stdin.write('$$FILE'+'&&'+active+'\n')
    
def clear():
    v1.set('')
    v2.set('')

class FlushFile(object): 
    def __init__(self, f):
        self.f = f
    def write(self, x):
        self.f.write(x)
        self.f.flush()
        
def Execute_File():
    global popen
    sys.stdout = FlushFile(sys.__stdout__)
    popen = subprocess.Popen(['java.exe' ,'-jar' ,'client.jar'], stdin=subprocess.PIPE,stdout = subprocess.PIPE)
    time.sleep(3);
    subprocess.Popen(['java.exe' ,'-jar' ,'udplisten.jar'], stdin=subprocess.PIPE,stdout = subprocess.PIPE)
    time.sleep(3);
    subprocess.Popen(['java.exe' ,'-jar' ,'tcplisten.jar'], stdin=subprocess.PIPE,stdout = subprocess.PIPE)

def Execute_File2(host, port):
    sys.stdout = FlushFile(sys.__stdout__)
    subprocess.Popen(['java.exe' ,'-jar' ,'udpsend.jar',host,port], stdin=subprocess.PIPE,stdout = subprocess.PIPE)

def Execute_File3(host, port, filepath):
    sys.stdout = FlushFile(sys.__stdout__)
    print 'java.exe' ,'-jar' ,'tcpsend.jar',host,port,filepath
    subprocess.Popen(['java.exe' ,'-jar' ,'tcpsend.jar',host,port,filepath], stdin=subprocess.PIPE,stdout = subprocess.PIPE)

def connect_server():
    Execute_File() 
    thread.start_new_thread(receive_thread, (popen,1)) # create thread for receiving stdout from subprocess
    thread.start_new_thread(get_active, (mylist,1))

"""
build GUI
"""
windows=Tk() #create windows
label0 = Label(windows,text='Client') #create project title
label0.pack()
    
f0=Frame(windows)
f0.pack(side=LEFT)

f01=Frame(f0)
f01.pack()
label1=Label(f01,text='Read')
label1.pack(side=LEFT)
v1 = StringVar()
Input1= Entry(f01, textvariable=v1,width=40,justify=LEFT)
Input1.pack(side=LEFT)
v1.set('')
    
f02=Frame(f0)
f02.pack()
label4 = Label(f02,text='Write')
label4.pack(side=LEFT)
v2 = StringVar()
Input5= Entry(f02, textvariable=v2,width=40,justify=LEFT)
Input5.pack(side=LEFT)
v2.set('')

f03=Frame(f0)
f03.pack()
but0=Button(f03, text='Connect')
but0.pack(side=LEFT)
but1=Button(f03, text='Stop')
but1.pack(side=LEFT)
but2=Button(f03, text='Send')
but2.pack(side=LEFT)
but3=Button(f03, text='Clear')
but3.pack(side=LEFT)
but4=Button(f03, text='Refresh')
but4.pack(side=LEFT)
but5=Button(f03, text='VideoChat')
but5.pack(side=LEFT)
but6=Button(f03, text='FileTransfer')
but6.pack(side=LEFT)

f1=Frame(windows)
f1.pack(side=RIGHT)
f11=Frame(f1)
f11.pack()
label11=Label(f11,text='ID')
label11.pack(side=LEFT)
v11 = StringVar()
Input1= Entry(f11, textvariable=v11,width=5,justify=LEFT)
Input1.pack(side=LEFT)
v11.set('')

label3=Label(f1,text='Active user')
label3.pack()
scrollbar = Scrollbar(f1)
scrollbar.pack( side = RIGHT, fill=Y )
mylist = Listbox(f1,  width=10, height=4, yscrollcommand = scrollbar.set )
mylist.insert(END, 'empty')
mylist.pack( fill = BOTH , expand=1)
scrollbar.config( command = mylist.yview )
but0.configure(command=connect_server)
but1.configure(command=stop)
but2.configure(command=send)
but3.configure(command=clear)
but4.configure(command=refresh)
but5.configure(command=videoC)
but6.configure(command=fileC)
windows.mainloop()


